package com.yaojianfeng.openai.controller;

import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.model.ChatModel;
import org.springframework.core.io.InputStreamResource;
import org.springframework.util.MimeTypeUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/multimodal")
public class OpenAIMultimodalController {
    private final ChatModel chatModel;

    public OpenAIMultimodalController(ChatModel chatModel) {
        this.chatModel = chatModel;
    }

    @PostMapping("/chat")
    public String chat(@RequestParam(value = "prompt", required = false) String prompt, @RequestParam(value = "image"
            , required = false) MultipartFile image) {
        return ChatClient.create(chatModel).prompt().user(u -> {
            try {
                u.text(prompt).media(MimeTypeUtils.IMAGE_PNG, new InputStreamResource(image.getInputStream()));
            }
            catch (IOException e) {
                throw new RuntimeException(e);
            }
        }).call().content();
    }
}
